package interface_layer;

import java.util.ArrayList;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import processing_layer.Course;
import processing_layer.CourseSession;
import database_layer.Common;
import database_layer.UpdateDispatcher;

/**
 * As it's named, this servlet handles the course additions in the
 * web service. It receives it's information from the corresponding JSP,
 * and communicates with the DB.
 */
public class CourseAddition extends HttpServlet
{
	private static final long serialVersionUID = 1L;
       
    public CourseAddition()
    {
        super();
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
	{
		try
		{
			String requestingAdmin = (String) request.getSession().getAttribute("username");
			
			if (null == requestingAdmin)
			{
				ErrorHandler.parseForErrors(Common.UNAUTHORIZED_OPERATION, response, null);
				return;
			}
			
			Course newCourse = new Course(request.getParameter("Course name"),
										  request.getParameter("Description"),
										  Float.parseFloat(request.getParameter("Credit points")),
										  Integer.parseInt(request.getParameter("Student capacity")),
										  0,
										  Integer.parseInt(request.getParameter("Group Number")),
										  requestingAdmin);
			
			String courseName = request.getParameter("Course name");
			int groupNumber = Integer.parseInt(request.getParameter("Group Number"));
			ArrayList<CourseSession> sessions = new ArrayList<CourseSession>();
			
			for (int i = 0 ; i < 5 ; i++)
			{
				int startingTime = Integer.parseInt(request.getParameter("starting_time_" + i));
				int duration = Integer.parseInt(request.getParameter("duration_" + i));
				int day = Integer.parseInt(request.getParameter("day_" + i));
				
				/* We made sure that all the fields are either 0 or either full */
				if (0 == startingTime)
				{
					continue;
				}
	
				CourseSession newSession = new CourseSession(courseName, day, startingTime,
					                                         startingTime + duration,
					                                         duration, groupNumber);			
				sessions.add(newSession);
			}
			
			int returnValue = UpdateDispatcher.addCourseAndSessions(newCourse, sessions);
			ErrorHandler.parseForErrors(returnValue, response, "allCourses.jsp");
		}
		catch (Exception e)
		{
			System.out.println("Exception is : " + e.getLocalizedMessage());
			ErrorHandler.parseForErrors(Common.INTERNAL_ERROR, response, null);
		}
	}
}
